<?php


namespace app\api\model;


use app\common\model\BaseModel;


class IdcModel extends BaseModel
{
    protected $name = 'idcard';

    public function is_cached($idcard, $username)
    {
        $rows = $this->where('idcno',$idcard)->field('name','status')->order('status','desc')->select();

        if (empty($rows)) {
            return -1;
        }

        foreach ($rows as $row) {
            $s = intval($row['status']);
            $n = $row['name'];
            if ($s == 0 || $s == 2) {
                if ($n == $username) {
                    return 0;
                }
            }
            elseif ($s == -1){
                if ($n != $username) {
                    return -1;
                }
            }
        }
        if (!empty($rows)) {
            return 1;
        }
        return -1;
    }

    function add($idcno, $name, $status, $extra = [])
    {
        $data = [
            'idcno' => $idcno,
            'name' => $name,
            'status' => $status,
            'create_time' => date('Y-m-d H:i:s')
        ];

        if ($status == 0 || $status == 2) {
            $info = \common::get_info_from_idcno($idcno);
            if ($info) {
                $data = array_merge($data, [
                    'gender' => $info['gender'],
                    'birthday' => $info['birthday'],
                ]);
            }
        }
        if (!empty($extra)) {
            if (isset($extra['imgs'])) {
                $data['imgs'] = $extra['imgs'];
            }
            if (isset($extra['auditor'])) {
                $data['auditor'] = $extra['auditor'];
            }
            if (isset($extra['nation'])) {
                $data['nation'] = $extra['nation'];
            }
            if (isset($extra['address'])) {
                $data['address'] = $extra['address'];
            }
            if (isset($extra['remark'])) {
                $data['remark'] = $extra['remark'];
            }
        }

        self::create($data,true);
    }

    function query_list($cd, $pos, $limit)
    {
        $selectlist = [
            'idcno' => 'string',
            'name' => 'string',
            'address' => 'string',
            'gender' => 'int',
            'imgs' => 'array',
            'remark' => 'string',
            'status' => 'int',
        ];

        $beans = [];
        if (array_key_exists('idcno', $cd) && !empty($cd['idcno'])) {
            $beans['idcno'] = $cd['idcno'];
        }
        if (array_key_exists('name', $cd) && !empty($cd['name'])) {
            $beans['name'] = $cd['name'];
        }

        if (empty($beans)) {
            return [];
        }

        $rows = $this->where($beans)->field(\common::array_keys($selectlist))->limit($pos,$limit)->select();

        if (empty($rows)) {
            return [];
        }

        return  $rows->toArray();
    }

}
